package com.hongya.article3.controller;

import com.hongya.article3.domain.UserEntity;
import com.hongya.article3.jpa.UserRespsitory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by hongyazhang on 2018/5/21.
 */
@RestController
@RequestMapping(value = "/user")
public class LoginControler {
    @Autowired
    private UserRespsitory userRespsitory;

    /**
     * 查询用户列表方法
     * @return
     */
    @RequestMapping(value ="/list" ,method = RequestMethod.GET)
    public List<UserEntity> list() {
        return userRespsitory.findAll();
    }

    /**
     * 登录
     * @return
     */
    @RequestMapping(value ="/login")
    public String login(UserEntity user, HttpServletRequest request) {
        String result =  "登陆成功";
        //登录成功
        boolean flag = true;
        //根据用户名查询用户是否存在
        UserEntity userEntity = userRespsitory.findOne(new Specification<UserEntity>() {
            @Override
            public Predicate toPredicate(Root<UserEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                criteriaQuery.where(criteriaBuilder.equal(root.get("name"),user.getName()));
                return null;
            }
        });
        if (userEntity ==null){
            result="您查询的用户不存在";
            flag=false;
        }else if (!userEntity.getPassword().equals(user.getPassword())){
            result="您查询的用户密码不正确";
            flag=false;
        }
        //登录成功
        if(flag){
            //将用户写入session
            request.getSession().setAttribute("_session_user",userEntity);
        }
        return result;
    }
}
